//创建用户相关小仓库
import { defineStore } from 'pinia'
// 引入接口
import UserAPI from '@/api'
//引入数据类型
import {LoginForm,LoginResponseData,UserInfoResponseData} from '@/api/user/type'
import {SET_TOKEN,GET_TOKEN,REMOVE_TOKEN}  from '@/utils/token'
// 引入路由(常量路由)
import {constantRoutes} from '@/router/routes'
import { RouteRecordRaw } from 'vue-router'

interface UserState{
        token:string | null,
        menuRoutes:RouteRecordRaw[],
        username:string,
        avatar:string
}
  

let useUserStore = defineStore('User', {
    //state:仓库存储数据的地方
    state: ():UserState => {
        return {
            token:GET_TOKEN() || '',//用户唯一标识token
            menuRoutes:constantRoutes,
            username:'',
            avatar:''
        }
    },
    //异步|逻辑的地方
    actions: {
        //用户登录
       async userLogin(userInfo:LoginForm) {
            const result:LoginResponseData = await UserAPI.user.login(userInfo)
            if(result.code === 200) {
                //登录成功
                //store存储token
                this.token = <string>result.data.token
                //本地持久化存储
                SET_TOKEN(<string>result.data.token)
                //能保证当前async函数返回一个promise 
                return 'ok'
            }else {
                //登录失败
                return Promise.reject(new Error(result.data.message))
            }
        },
        //获取用户信息方法
        async userInfo() {
            //获取用户信息进行存储【用户头像，用户名】
            const result:UserInfoResponseData = await <any>UserAPI.user.getUserInfo()
            if(result.code === 200) {       
                 this.username = result.data.checkUser.username
                 this.avatar = result.data.checkUser.avatar
                 return 'ok'
            }else {
                //获取用户信息失败
                return Promise.reject(new Error(result.data.message))
            }
        },
        //用户退出登录方法
         userLogout() {
            //可以处理登录的接口请求:退出登录接口（通知服务器本地用户唯一标识失效）  
            this.token = ''
            this.username = ''
            this.avatar = ''
            REMOVE_TOKEN()
        }
    },
    getters:{

    }
})

export default useUserStore